<script setup lang="ts">
import { useScrollViewRefresh, useSkeleton } from '@/composables'
import HotSkeleton from './components/HotSkeleton.vue'

import { getHotRecommendAPI } from '@/services/hot'
import type { HotPageParams, HotResult, SubTypeItem } from '@/types/hot'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'

// 热门推荐页 标题和url
const hotMap = [
  { type: '1', title: '特惠推荐', url: '/hot/preference' },
  { type: '2', title: '爆款推荐', url: '/hot/inVogue' },
  { type: '3', title: '一站买全', url: '/hot/oneStop' },
  { type: '4', title: '新鲜好物', url: '/hot/new' },
]

// 当前推荐页信息
let currentHot = hotMap[0]
// 热门推荐请求参数
let hotPageParams: HotPageParams = {
  // 环境变量，开发环境，修改初始页面方便测试分页结束
  page: import.meta.env.DEV ? 30 : 1,
  pageSize: 10,
}
// 封面图url
const bannerPicture = ref<string>()
// 热门推荐子项
const subTypes = ref<SubTypeItem[]>([])
// 热门推荐当前激活子项
const activeIndex = ref<number>(0)

// 获取热门推荐数据
const getHotRecommend = async () => {
  const res = await getHotRecommendAPI(currentHot.url, hotPageParams)
  bannerPicture.value = res.result.bannerPicture
  subTypes.value = res.result.subTypes
}

// 滚动到底加载更多数据
const onScrolltolower = async () => {
  const currentSubTypes = subTypes.value[activeIndex.value]
  const isbottomed = currentSubTypes.goodsItems.page >= currentSubTypes.goodsItems.pages
  if (isbottomed) {
    currentSubTypes.isFinished = true
    uni.showToast({
      title: '没有更多数据了~',
      icon: 'none',
    })
    return
  }
  currentSubTypes.goodsItems.page++
  hotPageParams.page = currentSubTypes.goodsItems.page
  hotPageParams.subType = currentSubTypes.id

  // 加载更多热门推荐数据
  const res = await getHotRecommendAPI(currentHot.url, hotPageParams)
  const newSubtypes = res.result.subTypes[activeIndex.value]
  currentSubTypes.goodsItems.items.push(...newSubtypes.goodsItems.items)
}

// 注入scroll-view组件下拉刷新组合逻辑
const { isTriggered, refreshController } = useScrollViewRefresh()

/**
 * 下拉刷新组件被触发，重置猜你喜欢组件的数据，并重新获取页面数据
 * refreshController是一个下拉刷新控制器，传入一个异步的回调函数，通常是获取数据的逻辑，
 * 获取数据前，isTriggered置为true，刷新动画打开，获取成功后，isTriggered置为false，关闭下拉刷新
 */
const onRefresherrefresh = () =>
  refreshController(async () => {
    // 重置请求参数
    hotPageParams = {
      // 环境变量，开发环境，修改初始页面方便测试分页结束
      page: import.meta.env.DEV ? 30 : 1,
      pageSize: 10,
    }
    // 重新获取页面数据
    await getHotRecommend()
  })

// 注入骨架屏组合式逻辑
const { isShowSkeleton, skeletonController } = useSkeleton()

onLoad(async (options) => {
  skeletonController(async () => {
    // 确定当前推荐页
    currentHot = hotMap.find((item) => item.type === options?.type) ?? hotMap[0]
    // 动态设置标题
    uni.setNavigationBarTitle({
      title: currentHot!.title,
    })
    // 获取热门推荐数据
    await getHotRecommend()
  })
})
</script>

<template>
  <!-- 骨架屏 -->
  <HotSkeleton v-if="isShowSkeleton" class="skeleton" />
  <view class="viewport" v-else>
    <!-- 推荐封面图 -->
    <view class="cover">
      <image :src="bannerPicture"></image>
    </view>
    <!-- 推荐选项 -->
    <view class="tabs">
      <text
        v-for="(item, index) in subTypes"
        :key="item.id"
        class="text"
        :class="{ active: activeIndex === index }"
        @tap="activeIndex = index"
        >{{ item.title }}</text
      >
    </view>
    <!-- 推荐列表 -->
    <scroll-view
      v-for="(item, index) in subTypes"
      :key="item.id"
      v-show="activeIndex === index"
      scroll-y
      class="scroll-view"
      refresher-enabled
      :refresher-triggered="isTriggered"
      @refresherrefresh="onRefresherrefresh"
      @scrolltolower="onScrolltolower"
    >
      <view class="goods">
        <navigator
          hover-class="none"
          class="navigator"
          v-for="goods in item.goodsItems.items"
          :key="goods.id"
          :url="`/pages/goods/goods?id=${goods.id}`"
        >
          <image class="thumb" :src="goods.picture"></image>
          <view class="name ellipsis">{{ goods.name }}</view>
          <view class="price">
            <text class="symbol">¥</text>
            <text class="number">{{ goods.price }}</text>
          </view>
        </navigator>
      </view>
      <view class="loading-text">{{ item.isFinished ? '没有更多数据了~' : '正在加载...' }}</view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
  background-color: #f4f4f4;
}
.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 180rpx 0 0;
  position: relative;
}
.cover {
  width: 750rpx;
  height: 225rpx;
  border-radius: 0 0 40rpx 40rpx;
  overflow: hidden;
  position: absolute;
  left: 0;
  top: 0;
}
.scroll-view {
  flex: 1;
}
.tabs {
  display: flex;
  justify-content: space-evenly;
  height: 100rpx;
  line-height: 90rpx;
  margin: 0 20rpx;
  font-size: 28rpx;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 5rpx rgba(200, 200, 200, 0.3);
  color: #333;
  background-color: #fff;
  position: relative;
  z-index: 9;
  .text {
    margin: 0 20rpx;
    position: relative;
  }
  .active {
    &::after {
      content: '';
      width: 40rpx;
      height: 4rpx;
      transform: translate(-50%);
      background-color: #27ba9b;
      position: absolute;
      left: 50%;
      bottom: 24rpx;
    }
  }
}
.goods {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 20rpx 20rpx;
  .navigator {
    width: 345rpx;
    padding: 20rpx;
    margin-top: 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }
  .thumb {
    width: 305rpx;
    height: 305rpx;
  }
  .name {
    height: 88rpx;
    font-size: 26rpx;
  }
  .price {
    line-height: 1;
    color: #cf4444;
    font-size: 30rpx;
  }
  .symbol {
    font-size: 70%;
  }
  .decimal {
    font-size: 70%;
  }
}

.loading-text {
  text-align: center;
  font-size: 28rpx;
  color: #666;
  padding: 20rpx 0 50rpx;
}
</style>
